<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium">
            <!-- <el-form-item>
              <el-button type="primary" @click="showAddForm">新增</el-button>
            </el-form-item> -->
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" @click="search">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="项目类型"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="carName"
        label="产品(车辆)名称"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="model"
        label="产品型号"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="costName"
        label="费用项目名称"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="num"
        label="数量"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="price"
        label="单价"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="unit"
        label="单位"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="totalPrice"
        label="成本价"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="totalPricePay"
        label="对外报价"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="costOther"
        label="费用类型"
        min-width="120">
        <template scope="scope">
          {{costOtherDate(scope.row.costOther)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="note"
        label="备注"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="createUserName"
        label="操作人"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="操作时间"
        min-width="160">
        <template scope="scope">
          {{fmtDate(scope.row.updateTime)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作"
        min-width="160">
        <template slot-scope="scope">
          <el-button size="mini" type="primary"  @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger"   @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="项目类型" label-width="100px" prop="name">
          <el-select v-model="editForm.name"   placeholder="请选择" style="width: 100%;"
          @change="getUnitPrice">
              <el-option
                v-for="item in TestWorkTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item v-if="editForm.name=='外部费用'" label="费用项目名称" label-width="100px" prop="costName">
          <el-input v-model="editForm.costName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="数量" label-width="100px" prop="num">
          <el-input v-model="editForm.num" type="number" autocomplete="off" @change="computed"></el-input>
        </el-form-item>
        <el-form-item label="单价" label-width="100px" prop="price">
          <el-input v-model="editForm.price" type="number" autocomplete="off" @change="computed"></el-input>
        </el-form-item>
        <el-form-item label="单位" label-width="100px" prop="unit">
          <el-input v-model="editForm.unit" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" label-width="100px" prop="totalPrice">
          <el-input v-model="editForm.totalPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="对外报价" label-width="100px" prop="totalPricePay">
          <el-input v-model="editForm.totalPricePay" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.note" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getTestPriceOtherListRecycle, addTestCostOther, updateTestCostOther, deleteTestGarageCost,getTestWorkTypeList} from "../../../api/test_garage_cost.js";
import {getAllTestSiteList} from '../../../api/test_site.js'
import {getToken} from '../../../common/utils/auth.js'
import {getTestCarList} from '../../../api/test_car.js'


export default {
  name: "priceOtherManage2",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      editForm: {
        id: 0,
        carId: '', // 车辆id
        name: '',
        price: '',
        num:'',
        totalPrice:'',
        totalPricePay:'',
        tOrderId:'',
        num:'',
        unit:'',
        note: '',
        carName:'',
        costOther:'',
        costName:'',
      },
      editRules: {
        name: [{ required: true, message:"请输入收费项目", trigger: 'blur'}],
        price: [{ required: true, message:"请输入单价", trigger: 'blur'}],
        num: [{ required: true, message:"请输入数量", trigger: 'blur'}],
        unit: [{ required: true, message:"请输入单位", trigger: 'blur'}],
        totalPrice: [{ required: true, message:"请输入成本价", trigger: 'blur'}],
        totalPricePay: [{ required: true, message:"请输入对外报价", trigger: 'blur'}],
      },
      loadingDiv: null,
      searchForm: {
        name: '',
        price: '',
        unit:'',
      },
      TestWorkTypeList:{
        id: 0,
        name: '',
        price: '',
        unit:'',
      },
      TestCarName:{

      },
      testSiteList:[],
      carId:'',
    }
  },
  computed:{

  },
  mounted() {
    let tOrderId=this.$route.params.tOrderId;
    this.tOrderId = tOrderId;

    this.init();

    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }

    let t = getToken();
    this.uploadActionUrl = this.$adminApiUrl + "/file/upload?_t="+t;
    this.fileBaseUrl = this.$adminApiUrl+"/file/get?_t="+t+"&f=";
  },
  methods: {
    init(){
      getAllTestSiteList().then(res => {
        if(res.code == 1) {
          this.testSiteList = res.data;
        }
      }).catch(res => {

      })
    },



    isEmpty(val){
      return util.isEmpty(val);
    },

    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2), fmt);
    },
    costOtherDate(data){
      if(data==1){
        return "其他费用";
      }
      return "现场费用";
    },

    showAddForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.last){
        this.editForm[key] = '';
      }

      this.editForm.carId = this.carId;
      this.editForm.id = 0;
      this.editFormVisible = true;




      this.editForm.name = '';
      this.editForm.price = '';
      this.editForm.totalPrice = '';
      this.editForm.totalPricePay = '';
      this.editForm.supplier = '';
      this.editForm.tOrderId = '';
      this.editForm.num = '';
      this.editForm.carEnterpriseName = '';
      this.editForm.averageMoney = '';
      this.editForm.userList = [];
      this.editForm.costName = '';
      this.editForm.unit = '';
      this.editForm.note = '';


    },
    computed(){
      this.editForm.totalPrice = this.editForm.price*this.editForm.num
      // if(this.editForm.totalPricePay==0||this.editForm.totalPricePay==''||this.editForm.totalPricePay==null){
      //   this.editForm.totalPricePay = this.editForm.totalPrice;
      // }
      this.editForm.totalPricePay = this.editForm.totalPrice;
    },
    getUnitPrice(){

      for(var i=0;i<this.TestWorkTypeList.length;i++){
        if(this.TestWorkTypeList[i].name == this.editForm.name){
        this.editForm.price = this.TestWorkTypeList[i].price;
        this.editForm.unit = this.TestWorkTypeList[i].unit;
        }
        this.editForm.totalPrice = this.editForm.price*this.editForm.num
      }
      this.editForm.tOrderId = this.tOrderId;
      this.editForm.costOther = 1;
    },


    handleEdit(index, row) {
    // console.log(editForm.costOther)

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = row[key];
      }
      this.editFormVisible = true;

      this.editForm.carName = this.editForm.carId

    },
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {
          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = updateTestCostOther
          if(this.editForm.id == 0){
            func = addTestCostOther
          }
          func(this.editForm).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.name+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestGarageCost({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getTestPriceOtherListRecycle({
        pageSize: this.pageSize,
        pageNum: pageNum,
        tOrderId: this.tOrderId,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
          this.last = data.last;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

      getTestCarList({
        pageSize: this.pageSize,
        pageNum: pageNum,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
           this.TestCarName = res.data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

      // getTestWorkTypeList().then(res => {
      //   if(res.code == 0) {
      //     this.$message({
      //       showClose: true,
      //       message: res.msg,
      //       type: 'error'
      //     });
      //   }else if(res.code == 1) {
      //      this.TestWorkTypeList = res.data;
      //   }
      //   loadingDiv.close();
      // }).catch(res => {
      //   loadingDiv.close();
      // })

    },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
